package com.sx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sx.dao.UserMapper;
import com.sx.domain.*;
import com.sx.service.UserService;
import com.sx.utils.Md5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 分页查询用户信息
     * @param userVo
     * @return
     */
    @Override
    public PageInfo findAllUserByPage(UserVo userVo) {
       // 防止空指针异常
       if (userMapper == null) {
           throw new RuntimeException("UserMapper未正确注入");
       }
       
       if (userVo == null) {
           throw new RuntimeException("UserVo参数不能为空");
       }
       
       // 设置默认分页参数
       int currentPage = userVo.getCurrentPage() == null ? 1 : userVo.getCurrentPage();
       int pageSize = userVo.getPageSize() == null ? 10 : userVo.getPageSize();
       
       //使用mybatis分页插件
       PageHelper.startPage(currentPage, pageSize);
       List<User> userByPage = userMapper.findUserByPage(userVo);
       PageInfo<User> userPageInfo = new PageInfo<>(userByPage);
       return userPageInfo;
    }

    @Override
    public void updateUserStatus(int id, String status) {
        userMapper.updateUserStatus(id, status);
    }

    @Override
    public User login(User user) {
        User login = userMapper.login(user);
        Md5 md5 = new Md5();
        try {
            if (login != null && md5.verify(user.getPassword(), Md5.md5key, login.getPassword())){
                return login;
            }else {
                return null;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Role> findUserRelationRoleById(Integer id) {
        List<Role> userRelationRoleById = userMapper.findUserRelationRoleById(id);
        return userRelationRoleById;
    }
    
    @Override
    public User findByPhone(String phone) {
        // 创建一个临时User对象用于查询
        User user = new User();
        user.setPhone(phone);
        return userMapper.login(user);
    }
    
    @Override
    public void register(User user) {
        // 参数校验
        if (user == null) {
            throw new RuntimeException("用户对象不能为空");
        }

        if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
            throw new RuntimeException("手机号不能为空");
        }

        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }

        // 设置默认值
        if (user.getName() == null || user.getName().trim().isEmpty()) {
            user.setName(user.getPhone()); // 默认使用手机号作为用户名
        }
        user.setStatus("ENABLE"); // 默认启用状态
        user.setAccount_non_expired(1); // 账号未过期
        user.setCredentials_non_expired(1); // 凭证未过期
        user.setAccount_non_locked(1); // 账号未锁定
        user.setIs_del(0); // 未删除
        user.setCreate_time(new Date()); // 创建时间
        user.setUpdate_time(new Date()); // 更新时间

        // 密码加密
        try {
            String encryptedPassword = Md5.md5(user.getPassword(), Md5.md5key);
            user.setPassword(encryptedPassword);
        } catch (Exception e) {
            throw new RuntimeException("密码加密失败", e);
        }

        // 调用Mapper保存用户
        userMapper.save(user);
    }

    @Override
    public void userContextRole(UserVo userVo) {
        //根据用户id清空中间表关系
        userMapper.deleteUserContextRole(userVo.getUserId());
        Date date = new Date();
        //再重新建立关联关系
        for (Integer roleId : userVo.getRoleIdList()) {
            User_Role_relation userRoleRelation = new User_Role_relation();
            userRoleRelation.setUserId(userVo.getUserId());
            userRoleRelation.setRoleId(roleId);
            userRoleRelation.setCreatedTime(date);
            userRoleRelation.setUpdatedTime(date);
            userRoleRelation.setCreatedBy("system");
            userRoleRelation.setUpdatedby("system");
            userMapper.userContextRole(userRoleRelation);
        }
    }

    @Override
    public ResponseResult getUserPermissions(Integer userid) {
        System.out.println("Getting permissions for user ID: " + userid);
        
        //获取当前用户获取的权限
        List<Role> userRelationRoleById = userMapper.findUserRelationRoleById(userid);
        System.out.println("Roles found for user: " + userRelationRoleById.size());

        //获取角色id，保存到List集合中
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (Role role : userRelationRoleById) {
            arrayList.add(role.getId());
        }
        System.out.println("Role IDs: " + arrayList);
        
        //如果没有角色，直接返回
        if (arrayList.isEmpty()) {
            return new ResponseResult(false, 400, "用户未分配角色", null);
        }
        
        //根据角色id查询父菜单
        List<Menu> parentMenuByRoleId = userMapper.findParentMenuByRoleId(arrayList);
        System.out.println("Parent menus found: " + parentMenuByRoleId.size());

        //查询封装父菜单关联的子菜单
        for (Menu menu : parentMenuByRoleId) {
            List<Menu> subMenuByPid = userMapper.findSubMenuByPid(menu.getId());
            menu.setSubMenuList(subMenuByPid);
            System.out.println("Sub menus for menu " + menu.getId() + ": " + subMenuByPid.size());
        }

        //获取资源信息
        List<Resource> resourceByRoleId = userMapper.findResourceByRoleId(arrayList);
        System.out.println("Resources found: " + resourceByRoleId.size());

        //封装数据并返回
        HashMap<String, Object> HashMap = new HashMap<>();
        HashMap.put("menuList", parentMenuByRoleId);
        HashMap.put("resourceList", resourceByRoleId);

        return new ResponseResult(true, 200, "获取用户权限成功", HashMap);


    }
}